<div class="archives-by-category">
  <h2>按分类归档</h2>
  <ul>
    <?php
      /*
        * @Description: 按分类取文章
        * @Autor: HuiSir<273250950@qq.com>
        * @Date: 2024-05-21 11:22:46
        * @LastEditTime: 2024-05-24 15:41:09
      */
      $categoryPosts = $wpdb->get_results("
      SELECT post_title, ID, post_name, slug, {$wpdb->prefix}terms.term_id AS catID, {$wpdb->prefix}terms.name AS categoryname
      FROM {$wpdb->prefix}posts, {$wpdb->prefix}term_relationships, {$wpdb->prefix}term_taxonomy, {$wpdb->prefix}terms
      WHERE {$wpdb->prefix}posts.ID = {$wpdb->prefix}term_relationships.object_id
      AND {$wpdb->prefix}terms.term_id = {$wpdb->prefix}term_taxonomy.term_id
      AND {$wpdb->prefix}term_taxonomy.term_taxonomy_id = {$wpdb->prefix}term_relationships.term_taxonomy_id
      AND {$wpdb->prefix}term_taxonomy.taxonomy = 'category'
      AND {$wpdb->prefix}posts.post_status = 'publish'
      AND {$wpdb->prefix}posts.post_type = 'post'
      ORDER BY {$wpdb->prefix}terms.term_id, {$wpdb->prefix}posts.post_date DESC");

      $postID = 0;
      if ( $categoryPosts ) :
        $category = $categoryPosts[0]->catID;
        foreach ($categoryPosts as $key => $mypost) :
          if($postID == 0) {
            echo '<li><span class="title">分类：'.$mypost->categoryname.'</span>';
            echo '<ul>';
          }
            
          if($category == $mypost->catID) {          
    ?>
      <li><a title="<?php echo $mypost->post_title; ?>" href="<?php echo get_permalink( $mypost->ID ); ?>"><?php echo $mypost->post_title; ?></a></li>
    <?php
            $category = $mypost->catID;
            $postID++;
          }
          else {
            echo "</ul>\n</li>";
            echo '<li><span class="title">分类：'.$mypost->categoryname.'</span>';
            echo '<ul>';
    ?>
      <li><a title="<?php echo $mypost->post_title; ?>" href="<?php echo get_permalink( $mypost->ID ); ?>"><?php echo $mypost->post_title; ?></a></li>
    <?php
            $category = $mypost->catID;
            $postID = 1;
          }
        endforeach;
      endif;
      echo "</ul>\n</li>";
    ?>
    <li>
      <span class="title">页面</span>
      <ul>
        <?php
        /*
          * @Description: 读取所有页面
          * @Autor: HuiSir<273250950@qq.com>
          * @Date: 2024-05-21 11:26:10
          * @LastEditTime: 2024-05-21 17:18:45
        */
        $allPages = $wpdb->get_results("
          SELECT post_title, post_name, ID
          FROM {$wpdb->prefix}posts
          WHERE post_status = 'publish'
          AND post_type = 'page'");

        if ( $allPages ) :
          foreach ($allPages as $thePage) :
        ?>
      <li><a title="<?php echo $thePage->post_title; ?>" href="<?php echo get_permalink( $thePage->ID ); ?>"><?php echo $thePage->post_title; ?></a></li>
    <?php endforeach; echo "</ul>\n</li>"; endif; ?>
  </ul>
</div>